package cn.gov.ssxmzj.service;

import cn.gov.ssxmzj.entry.News;
import cn.gov.ssxmzj.entry.PageNews;
import cn.gov.ssxmzj.entry.Result;
import cn.gov.ssxmzj.entry.ServiceInfo;
import cn.gov.ssxmzj.mapper.NewsMapper;
import cn.gov.ssxmzj.mapper.ServiceMapper;
import cn.gov.ssxmzj.utils.StaticUtils;
import cn.gov.ssxmzj.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class NewsService {

    @Autowired
    private NewsMapper newsMapper;

    @Autowired
    private ServiceMapper serviceMapper;

    //获取所有的新闻
    public Result getNews(){
        List<News> news = newsMapper.getNews();
        //最新动态
        List<Map<String,String>> Rules = new ArrayList<Map<String,String >>();
        //民政要闻
        List<Map<String,String>> Standard = new ArrayList<Map<String,String >>();
        //公示公告
        List<Map<String,String>> companyGsggs = new ArrayList<Map<String,String >>();
        //政策法规
        List<Map<String,String>> companyViews = new ArrayList<Map<String,String >>();
        //轮播图片
        List<Map<String,String>> focusList = new ArrayList<Map<String,String >>();
        for (News theNew:news) {
            Map<String, String> newMap = new HashMap<String, String>();
            //1-最新动态;2-民政要闻;3-公示公告;4-政策法规;5-轮播图
            if ("5".equals(theNew.getNews_type())) {//先处理轮播图
                newMap.put("id", theNew.getNews_id());
                newMap.put("name", theNew.getNews_name());
                newMap.put("text", theNew.getNews_title());
                newMap.put("src", theNew.getNews_pic_src());
                newMap.put("alt", "");
                focusList.add(newMap);
            } else {
                newMap.put("id", theNew.getNews_id());
                newMap.put("title", theNew.getNews_title());
                String time = null == theNew.getLast_change_time() ? theNew.getCreate_time() : theNew.getLast_change_time();
                newMap.put("time", time.substring(4, 6)+"-"+time.substring(6,8));
                if ("1".equals(theNew.getNews_type())) {
                    Rules.add(newMap);
                } else if ("2".equals(theNew.getNews_type())) {
                    Standard.add(newMap);
                } else if ("3".equals(theNew.getNews_type())) {
                    companyGsggs.add(newMap);
                } else if ("4".equals(theNew.getNews_type())) {
                    companyViews.add(newMap);
                }
            }
        }
        //获取惠民资金的内容
        Map sqlMap = Utils.asMap("serviceType","2","validTag","1");
        List<ServiceInfo> serviceInfos = serviceMapper.getServiceInfoByType(sqlMap);
        Map retMap = Utils.asMap("news", Utils.asMap("Rules",Rules,"Standard",Standard),"companyGsggs",
                companyGsggs,"companyViews",companyViews,"focusList",focusList,"serviceInfos",serviceInfos);
        return new Result(Result.SUCCESS,"查询成功",retMap);
    }

    //根据新闻id获取新闻内容
    public Result getNewById(String newsId,boolean isManager){
        List<News> news = newsMapper.getNewsById(newsId);
        //管理员查询时,直接返回整个新闻实体
        if(isManager){
            return new Result(Result.SUCCESS,"查询成功",news);
        }
        String html = null;
        if(Utils.isEmpty(news)){
            html = "<div style='font-size:120%;text-align: center;'>未查询到该内容，请刷新首页重试</div>";
        }else if("0".equals(news.get(0).getValid_tag())){
            html = "<div style='font-size:120%;text-align: center;'>该内容已被删除，去看看其他的吧</div>";
        }else {
            html = "<h1 style='font-size:200%;text-align: center;'>" + news.get(0).getNews_title() + "</h1></br>"+
                    (Utils.isEmpty(news.get(0).getNews_pic_src())?"":"<img src='"+news.get(0).getNews_pic_src()+"'>")+
                    "</br> <font style='font-size:120%;'>" + news.get(0).getNews_content() + "</font>";
        }
        return new Result(Result.SUCCESS,"查询成功",html);
    }

    /**
     * 根据新闻类型获取全部的新闻内容
     * @param newsType
     * @param offset
     * @param rows
     * @return
     */
    public Result getAllNewByType(String newsType,int offset,int rows){
        offset = offset==0 ? 0 : --offset;
        offset = offset*rows;
        String type = Utils.changeNewsType(newsType,true);
        if(Utils.isEmpty(type)){
            return new Result(Result.ERROR,"新闻类型有误!"+"["+newsType+"]","");
        }
        //获取有效数据总条数
        Map sqlMap = Utils.asMap("newsType",type,"validTag","1");
        int count = newsMapper.getNewsCountByType(sqlMap);
        if(count <= 0){
            return new Result(Result.SERVICE_ERROR,"暂无该内容","");
        }
        //返回新闻内容
        List<Map<String,String>> newsData = new ArrayList<Map<String,String >>();
        sqlMap.putAll(Utils.asMap("offset",offset,"rows",rows));
        List<News> news = newsMapper.getAllNewsByType(sqlMap);
        for(News theNew:news){
            String time = null == theNew.getLast_change_time() ? theNew.getCreate_time() : theNew.getLast_change_time();
            newsData.add(Utils.asMap("id", theNew.getNews_id(),"title", theNew.getNews_title(),"time",
                    time.substring(4, 6)+"-"+time.substring(6,8)));
        }
        return new Result(Result.SUCCESS,"查询成功",new PageNews(count,Utils.asMap("newsData",newsData)));
    }

    /**
     * 获取下载文件列表
     * @return
     */
    public Result getDownloadFileList(){
        //下载列表所在文件夹
        File file = new File(StaticUtils.IMAGE_ROOT+StaticUtils.DOWNLOAD_FILE_PATH);
        File[] files = file.listFiles();
        if(Utils.isEmpty(files)){
            return new Result(Result.SERVICE_ERROR,"<div style='text-align:center'>暂无下载文件</div>","");
        }
        String fileList = "<div style='font-size:120%'>";
        for(File f:files){
            //显示的文件名需要加上项目名,防止出现路径问题
            String fileName = StaticUtils.DB_IMAGE_ROOT+StaticUtils.DOWNLOAD_FILE_PATH+f.getName();
            fileList += "<a style='color: blue' href='"+fileName+"'>"+f.getName()+"</a><br>";
        }
        return new Result(Result.SUCCESS,"查询成功",fileList+"</div>");
    }

    /**
     * 上传新闻图片
     * @param file
     * @return
     */
    public Map uploadNewsPic(MultipartFile file){
        String picName = file.getOriginalFilename();
        //图片类型
        String picType = picName.substring(picName.indexOf(".")+1);
        String fileName = Utils.createShowPicId()+"."+picType;
        //图片的相对路径
        String filePath = StaticUtils.SHOW_PIC_PATH + fileName;

        try {
            Utils.uploadFile(file, StaticUtils.IMAGE_ROOT + filePath);
        }catch (Exception e){
            e.printStackTrace();
            return Utils.asMap("code","1","msg","上传失败");
        }

        return Utils.asMap("code","0","msg","上传成功","data",Utils.asMap(
                "src",StaticUtils.DB_IMAGE_ROOT+filePath,"title","新闻图片丢失"));
    }
}
